<!--
 * @Author: wjk
 * @Date: 2019-12-31 15:40:51
 * @LastEditors: wjk
 * @LastEditTime: 2019-12-31 15:51:20
 * @description: file content
 -->
<template>
  <base-page-view class-name="page-container red-packet-container" :style-text="'background-image: url(' + backgroundImg + ')'" @touchstart="playBgMusic">
    <template v-if="!pageLoading">
      <template v-if="activityData && activityData.state < 3">
        <!-- 活动预告 -->
        <template v-if="activityData.restTimeToStart > 60">
          <view v-if="showRule" class="rule-modal">
            <view class="container">
              <view class="title">规则详情</view>
              <view class="detail">
                <rich-text :nodes="ruleContent"></rich-text>
              </view>
            </view>
            <image class="close-btn" :src="require('./assets/close-btn.png')" mode="widthFix" @click="showRule=false" />
          </view>
          <template v-else-if="activityData.startTime">
            <image class="rule-btn" :style="'top: '+ruleTop+'px'" :src="require('./assets/activity-rule.png')" mode="widthFix" @click="showRule=true" />
            <view class="time-modal" :style="'background-image: url(' + timeBg + ')'">
              <view class="time">{{ activityData.startTime.split(' ')[1] }}</view>
              <image class="back-btn" :src="require('./assets/back-btn.png')" mode="widthFix" @click="toBack" />
            </view>
          </template>
        </template>

        <!-- 倒计时 60s 活动开始 -->
        <template v-else-if="activityData.restTimeToStart > 0">
          <view class="time-to-start-modal">
            <view style="position: relative">
              <image class="wing" :src="wingImg" mode="aspectFit" />
              <view class="count-block" :style="'background-image: url(' + countBg + ')'">
                <view class="title">倒计时</view>
                <view class="flex-container">
                  <view>{{ parseInt(activityData.restTimeToStart/10) }}</view>
                  <view>{{ activityData.restTimeToStart%10 }}</view>
                  <!-- <div>S</div> -->
                </view>
              </view>
            </view>
            <image class="text" :src="textImg" mode="widthFix" />
          </view>
        </template>

        <!-- 倒计时 30s 活动结束 -->
        <template v-else-if="activityData.restTimeToStop > 0">
          <view class="activity-data-block">
            <view class="time-part">
              <view class="title">倒计时</view>
              <view>{{ activityData.restTimeToStop }}s</view>
            </view>
            <div class="sub-item">已抢红包个数：{{ getPacketNumber }}</div>
          </view>
          <view id="red-packets-block" class="red-packets-block">
            <template v-for="(item, index) in redPackets">
              <view v-if="item.show" :key="index" :style="{ left: item.left, animationDuration: item.durTime, webkitAnimationDuration: item.durTime}" :class="item.cls" @click="clickPacket($event, item)">
                <view href="javascript:;">
                  <view class="packet" :style="{ transform: item.transforms, webkitTransform: item.transforms, 'background-image': 'url(' + packetImg + ')'}"></view>
                </view>
              </view>
            </template>
          </view>
          <template v-for="(item, index) in numberPoints">
            <view
              v-if="item.show"
              :key="index"
              class="number-point"
              :style="{ left: item.left, top: item.top, animationDuration: '1s', webkitAnimationDuration: '1s'}">
              + 1
            </view>
          </template>
        </template>

        <!-- 红包金额计算中 -->
        <template v-else-if="activityData.state === 2 && calculateState">
          <view class="modal" :style="'background-image: url('+modalBg+')'">
            <view class="flex-container">
              <view>活动结束</view>
              <view class="text">红包金额结算中...</view>
            </view>
          </view>
        </template>

        <!-- 显示红包金额 -->
        <template v-else-if="showResult">
          <view class="result-modal" :style="'background-image: url('+moneyBg+')'">
            <view class="money">{{ resultMoney }}</view>
            <view class="btns">
              <image :src="btnUse" mode="aspectFit" @click="toUse" />
              <image :src="btnView" mode="aspectFit" @click="$navigateTo('/pagesMine/my-red-packets/index?from=redPackets')" />
            </view>
            <image class="back-btn" :src="require('./assets/back-btn.png')" mode="widthFix" @click="toBack" />
          </view>
        </template>
      </template>
      <view v-else class="modal end-modal" :style="'background-image: url('+modalBg+')'">
        <view class="flex-container">活动已结束</view>
        <image class="back-btn" :src="require('./assets/back-btn.png')" mode="widthFix" @click="toBack" />
      </view>
    </template>
  </base-page-view>
</template>

<script>
import { parseHtmlSync } from '@/components/jyf-Parser/libs/MpHtmlParser'
import { toFunctionDetail, toMpHomePage, toBackPage } from '@/utils/navigateTo'
import './index.scss'

let maxSubmitNumber = 40
export default {
  components: {
  },
  data() {
    return {
      page_need_login: true,
      pageLoading: false,

      timer: null,
      screenWidth: 375,
      redPackets: [],
      numberPoints: [],
      getPacketNumber: 0,
      calculateState: false,
      showResult: false,
      resultMoney: 0,

      ruleTop: 64,
      ruleContent: [],
      activityData: {
        startTime: ''
      },
      backgroundImg: '',
      bgMusicContext: null,
      startMusicContext: null,

      modalBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/red-packet/modal_bg.png`,
      timeBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/red-packet/time_bg.png`,
      countBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/red-packet/count_bg.png`,
      moneyBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/red-packet/money_bg.png`,
      wingImg: `${process.env.VUE_APP_IMAGE_ASSET}/images/red-packet/wing.png`,
      textImg: `${process.env.VUE_APP_IMAGE_ASSET}/images/red-packet/text.png`,
      packetImg: `${process.env.VUE_APP_IMAGE_ASSET}/images/red-packet/packet.png`,
      btnView: `${process.env.VUE_APP_IMAGE_ASSET}/images/red-packet/btn_view.png`,
      btnUse: `${process.env.VUE_APP_IMAGE_ASSET}/images/red-packet/btn_use.png`,

      showRule: false
    }
  },
  created() {
    const res = uni.getSystemInfoSync()
    this.screenWidth = res.screenWidth
    this.ruleTop = res.statusBarHeight ? (res.statusBarHeight + 44 + 20) : 24
  },
  onLoad() {
    this.$setNavTitle('红包雨', true)
    this.fetchData()
  },
  onHide() {
    this.stopBgMusic()
  },
  methods: {
    initData() {
      this.bgMusicContext = uni.createInnerAudioContext()
      this.bgMusicContext.autoplay = true
      this.bgMusicContext.loop = true
      this.bgMusicContext.src = `${process.env.VUE_APP_IMAGE_ASSET}/music/bgMusic.mp3`
      this.bgMusicContext.onError((res) => {
        console.log('bgMusicContext onError', res)
      })

      // #ifdef H5
      document.addEventListener('WeixinJSBridgeReady', () => {
        this.bgMusicContext.play()
      }, false)
      document.addEventListener('YixinJSBridgeReady', () => {
        this.bgMusicContext.play()
      }, false)
      // #endif

      this.startMusicContext = uni.createInnerAudioContext()
      this.startMusicContext.src = `${process.env.VUE_APP_IMAGE_ASSET}/music/startMusic.mp3`
      this.startMusicContext.onError((res) => {
        console.log('startMusicContext onError', res)
      })
    },
    async fetchData() {
      this.pageLoading = true
      const res = await this.$api.redPacketApi.getActivity()
      if (res.success && res.data) {
        this.initData()
        this.activityData = res.data
        this.backgroundImg = this.activityData.backgroundPic
        this.ruleContent = parseHtmlSync(this.activityData.activityRule) || []
        if (this.activityData.restTimeToStart > 0) {
          this.activityData.restTimeToStop = this.activityData.duration
          const interval = setInterval(() => {
            this.activityData.restTimeToStart--
            if (this.activityData.restTimeToStart < 2) {
              this.startMusicContext.play()
            }
            if (this.activityData.restTimeToStart < 0) {
              this.activityData.state = 2
              clearInterval(interval)
              this.startActivity()
            }
          }, 1000)
          this.$on('hook:deactivated', () => {
            clearInterval(interval);                                    
          })
        } else if (this.activityData.state === 2) {
          this.startActivity()
        }
      } else {
        const baseRes = await this.$api.redPacketApi.getBaseInfo()
        if (baseRes.success && baseRes.data) {
          this.backgroundImg = baseRes.data.picUrl
        }
      }
      this.pageLoading = false
    },
    startActivity() {
      this.addRedPacket()
      const intervalTimer = setInterval(() => {
        this.activityData.restTimeToStop--
        if (!(this.activityData.restTimeToStop > 0)) {
          clearTimeout(this.timer)
          clearInterval(intervalTimer)

          this.calculateState = true
          setTimeout(() => {
            this.submitResult()
          }, (parseInt(Math.random() * 10) % 5) * 1000)
        }
      }, 1000)
      this.$on('hook:deactivated', () => {
        clearInterval(intervalTimer);                                    
      })
    },
    addRedPacket() {
      const left = parseInt(Math.random() * (this.screenWidth - 88) + 0)
      const rotate = (parseInt(Math.random() * (45 - (-45)) - 45)) + 'deg'
      const scale = (Math.random() * (12 - 8 + 1) + 8) * 0.04
      const durTime = (Math.random() * (2.5 - 1.2 + 1) + 1.2) // 时间  1.2和1.2这个数值保持一样
      this.redPackets.push({
        left: `${left}px`,
        cls: 'move',
        transforms: `rotate(${rotate}) scale(${scale})`,
        durTime: durTime + 's',
        show: true
      })

      const index = this.redPackets.length
      const timeToRemove = durTime * 5000
      console.log('clear start', index, timeToRemove)
      const t = setTimeout(() => {
        if (this.redPackets[index - 1]) {
          console.log('clear end at ', index, timeToRemove)
          this.redPackets[index - 1].show = false
        }
        clearTimeout(t)
      }, timeToRemove)

      const length = this.redPackets.filter(i => i.show).length
      this.timer = setTimeout(() => {
        this.addRedPacket()
      }, parseInt(Math.random() * 36) * (length || 10))
    },
    clickPacket(e, item) {
      const music = uni.createInnerAudioContext()
      music.src = `${process.env.VUE_APP_IMAGE_ASSET}/music/click.mp3`
      music.autoplay = true
      music.loop = false
      this.numberPoints.push({
        left: `${e.detail.x}px`,
        top: `${e.detail.y}px`,
        show: true
      })
      const index = this.numberPoints.length
      const t = setTimeout(() => {
        if (this.numberPoints[index - 1]) {
          this.numberPoints[index - 1].show = false
        }
        clearTimeout(t)
      }, 1000)

      this.getPacketNumber++
      this.remove(item)
    },
    remove(item) {
      item.show = false
    },
    playBgMusic() {
      if (this.activityData && this.activityData.state < 3 && this.bgMusicContext.paused) {
        this.bgMusicContext.play()
      }
    },
    stopBgMusic() {
      this.bgMusicContext.stop()
    },
    async submitResult() {
      const res = await this.$api.redPacketApi.submitPacket({
        hongbaoNumber: this.getPacketNumber,
        hongbaoRainActivityId: this.activityData.hongbaoRainActivityId,
        hideLoading: true
      })
      if (res.success) {
        this.getResult()
      } else if (maxSubmitNumber > 0) {
        maxSubmitNumber--
        setTimeout(this.submitResult, 500)
      } else {
        this.getResult()
      }
    },
    getResult() {
      let maxGetNumber = 100
      const resultTimer = setInterval(async() => {
        maxGetNumber--
        const res = await this.$api.redPacketApi.getPacketMoney({
          hongbaoRainActivityId: this.activityData.hongbaoRainActivityId,
          hideLoading: true
        })
        if ((res.success && res.data) || maxGetNumber === 0) {
          this.resultMoney = res.data || 0
          this.calculateState = false
          this.showResult = true
          clearInterval(resultTimer)
        }
      }, 2000)
      this.$on('hook:deactivated', () => {
        clearInterval(resultTimer);                                    
      })
    },
    toUse() {
      const url = this.activityData.useLink
      if (url) {
        toFunctionDetail({
          type: 0,
          type_val: url
        })
      } else {
        toMpHomePage()
      }
    },
    toBack() {
      toBackPage()
    }
  }
}
</script>
